<?php
/**
 * Created by PhpStorm.
 * User: cth
 * Date: 2017/6/13
 * Time: 上午10:13
 */
/***
 *
 *
 *                                                    __----~~~~~~~~~~~------___
 *                                   .  .   ~~//====......          __--~ ~~
 *                   -.            \_|//     |||\\  ~~~~~~::::... /~
 *                ___-==_       _-~o~  \/    |||  \\            _/~~-
 *        __---~~~.==~||\=_    -_--~/_-~|-   |\\   \\        _/~
 *    _-~~     .=~    |  \\-_    '-~7  /-   /  ||    \      /
 *  .~       .~       |   \\ -_    /  /-   /   ||      \   /
 * /  ____  /         |     \\ ~-_/  /|- _/   .||       \ /
 * |~~    ~~|--~~~~--_ \     ~==-/   | \~--===~~        .\
 *          '         ~-|      /|    |-~\~~       __--~~
 *                      |-~~-_/ |    |   ~\_   _-~            /\
 *                           /  \     \__   \/~                \__
 *                       _--~ _/ | .-~~____--~-/                  ~~==.
 *                      ((->/~   '.|||' -_|    ~~-/ ,              . _||
 *                                 -_     ~\      ~~---l__i__i__i--~~_/
 *                                 _-~-__   ~)  \--______________--~~
 *                               //.-~~~-~_--~- |-------~~~~~~~~
 *                                      //.-~~~--\
 *                              神兽保佑
 *                              代码无BUG!
 */
namespace App\Repositories;

use App\Models\User;
use App\Models\WeixinUser;
use App\Models\UserCheck;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use App\Models\Shop;
use App\Models\ShopMenu;
use App\Models\ShopDish;
use App\Models\ShopDishAttribute;
use App\Models\Order;
use App\Models\Address;
use App\Tools\Map;
use App\Tools\SqlIncrement;
use App\Tools\MoneyChange;
use App\Tools\Activity;
class TakeoutRepository
{
    //获取菜单
    public function getshopMenu($id)
    {
        $menu = ShopMenu::where('shop_id',$id)->orderBy('menu_sort','ASC')->get();
        if($menu){
            $menu = $menu->toArray();
        }
        //处理空菜单
        foreach($menu as $k=>$v){
            $checkdish = ShopDish::where('menu_id',$v['id'])->where('status',1)->first();
            if(!$checkdish){
                unset($menu[$k]);
            }
        }
        //获取商家信息
        $shop = Shop::find($id);

        if($shop){
            $shop['shopinfo'] = $shop->shopinfo;
            $shop['menu'] = array_merge($menu);
        }
        return $shop;
    }

    //获取菜式
    public function getIdshopdish($id){
         //获取相应的菜式
         $dishes = ShopDish::where('menu_id',$id)->where('status',1)->get()->toArray();
         //return $dishes;
         //判断多规格
         foreach($dishes as $k=>$v){
             if (strpos($v['thumb'],';')){
                 $res = explode(';',$v['thumb']);
                 $dishes[$k]['thumb']=$res[0];
             }
             if($v['is_attr']==1){
                 $dishes[$k]['attribute'] = ShopDishAttribute::where('dish_id',$v['id'])->get();
                 //处理多规格
                 for($y=0;$y<count($dishes[$k]['attribute']);$y++)
                 {
                     $spec=explode(",", $dishes[$k]['attribute'][$y]['spec']);
                     foreach($spec as $k2=>$v2)
                     {
                         $spec[$k2] = explode("|",$v2);
                         $specend[$k2]['spec_name'] = $spec[$k2][0];
                         $specend[$k2]['spec_price'] = $spec[$k2][1];
                     }
                     $dishes[$k]['attribute'][$y]['spec']=$specend;
                 }
             }
         }
         return $dishes;
    }

    //确定下单
    public function addOrder($cart,$coupon_id=false){
        //$coupon_id = 1;
        //验证购物车
        if(empty($cart) || empty($cart['dish'])){
            return show("30003","购物车不存在！","");
        }
        //验证商家
        $shop = Shop::find($cart["shop_id"]);
        if(!$shop){
            return show("30001","店铺不存在或未审核！","");
        }
        if($shop->is_takeout!=1){
            return show("30001","该商铺未开通外卖功能");
        }
        //店铺休息
        if($shop->shopinfo->is_open==0){
            return show("30001","店铺已打烊！","");
        }
        //营业时间
        $opentimes = explode(',',$shop->shopinfo->opentime);
        $check_time =0;
        foreach($opentimes as $k=>$v){
            $opentime =explode('--',$v);
            if(strtotime($opentime[0])<=time() && strtotime($opentime[1])-900>=time()){
                $check_time +=1;
            }else{
                $check_time +=0;
            }
        }
        if($check_time==0){
            return show("30001","这个点不送外卖");
        }
        //验证地址
        $address = Address::find($cart["address_id"]);
        if(!$address){
            return show("30002","地址不存在！","");
        }
        if($address["user_id"]!=Auth::id()){
            return show("30002","非此用户地址！","");
        }
        $Uaddress=Map::getLngLat($address["address"]);
        if($Uaddress==''){
            return show("30002","用户地址填写有误！","");
        }
        //验证距离
        $distance = calcDistance($Uaddress['lat'], $Uaddress['lng'],$shop['latitude'],$shop['longitude']);
        if($distance > ($shop->shopinfo->spend_distance)){
            return show("30001","不在配送范围！","");
        }
        //验证价格(除非你有更好的方法否则别乱来)
        $top_amount=$top_price = 0;
        foreach($cart['dish'] as $k=>$v)
        {
            $dishes = ShopDish::find($v['dishes_id']);
            if($dishes) {
                $dishes = $dishes->toArray();
                if ($dishes['is_attr'] == 1) {
                    //获取数据库的规格计算
                    $ShopDishAttribute = ShopDishAttribute::where('dish_id', $dishes['id'])->get();
                    $spec_price = 0;
                    foreach ($ShopDishAttribute as $k2 => $v2) {
                        foreach (explode(',', $v2['spec']) as $k3 => $v3) {
                            $spec = explode('|', $v3);
                            //获取购物车的规格计算
                            $cart_dish_spec = explode(',', $cart['dish'][$k]['spec']);
                            foreach ($cart_dish_spec as $k4 => $v4) {
                                $cart_spec = explode('|', $v4);
                                if ($cart_spec[0] == $spec[0]) {
                                    $spec_price += floatval($spec[1]);
                                }
                            }
                        }
                    }
                    //（规格价+基础价）* 数量 * 折扣
                    $top_amount += ($spec_price + $dishes['price']) * $cart['dish'][$k]['goods_number'] * $dishes['discount'];
                    $top_price += ($spec_price + $dishes['price']) * $cart['dish'][$k]['goods_number'];
                } else {
                    $top_amount += $dishes['price'] * $cart['dish'][$k]['goods_number'] * $dishes['discount'];
                    $top_price += $dishes['price'] * $cart['dish'][$k]['goods_number'];
                }
            }

        }
        //强转防止溢出
        $top_amount = round($top_amount,2)+$shop->shopinfo->spend;
        if($top_amount!=$cart['top_price']){
            return show("30003","购物车异常！",["top_price" => $top_amount]);
        }
        //未达起送价！
        if($top_amount<$shop->shopinfo->min_spend){
            return show("30003","未达起送价！");
        }
        //生成订单
        $insert=Order::create([
              "user_id"=>Auth::id(),      //用户id
              "shop_id"=>$cart["shop_id"],//商铺id
              "order_type"=>0,            //外卖
              "order_number"=>randID(),   //订单编号
              "order_status"=>1,          //订单状态
              "note"=>$cart['note'],      //订单备注
              "address_id"=>  $cart['address_id'], //配送地址id
              "order_price"=>$top_amount,         //订单总价
              "order_amount"=>$top_amount,       //实际价格
              "product_type"=>1,                 //餐饮模块（1）
        ]);
        //处理详情
        foreach($cart['dish'] as $k=>$v){
            $cart['dish'][$k]['order_id']=$insert['id'];
            $cart['dish'][$k]['amount']  = $cart['dish'][$k]['sell_price'] = $v['goods_number']*$v['price'];
        }
        DB::table('order_details')->insert($cart["dish"]);
        if($coupon_id){//使用优惠券
            $activity =new Activity();
            $activity->activity($insert['id'],2,$coupon_id);
        }
        return show("200","下单成功",["order_id"=>$insert['id'],"money"=>$top_amount,"order_type"=>0]);
    }

    // 小程序下单
    public function addOrderProgram($cart,$coupon_id=false){
        $cart = $cart[0];
        //验证购物车
        if(empty($cart) || empty($cart['dish'])){
            return show("30003","购物车不存在！","");
        }
        //验证商家
        $shop = Shop::find($cart["shop_id"]);
        if(!$shop){
            return show("30001","店铺不存在或未审核！","");
        }
        if($shop->is_takeout!=1){
            return show("30001","该商铺未开通外卖功能");
        }
        //店铺休息
        if($shop->shopinfo->is_open==0){
            return show("30001","店铺已打烊！","");
        }
        $token = $cart['token'];
        if(!$token){//auth验证
            if(!Auth::id())
            {
                return  show('30001','请登录后再充值');
            }
            $user_id = Auth::id();
        }else{//token验证

            $WeixinUser = WeixinUser::where('token',$token)->first();
            if(!$WeixinUser){
                return show("30001","无效token！");
            }else{
                $user= User::find($WeixinUser->user_id);
                if(!$user){
                    return show("30001","用户不存在！");
                }
            }
            $user_id = $WeixinUser->user_id;
        }
        try{


        //营业时间
        $opentimes = explode(',',$shop->shopinfo->opentime);
        $check_time =0;
        foreach($opentimes as $k=>$v){
            $opentime =explode('--',$v);
            if(strtotime($opentime[0])<=time() && strtotime($opentime[1])-900>=time()){
                $check_time +=1;
            }else{
                $check_time +=0;
            }
        }
        if($check_time==0){
            return show("30001","这个点不送外卖");
        }
        //验证地址
        $address = Address::find($cart["address_id"]);
        if(!$address){
            return show("30002","地址不存在！","");
        }
        if($address["user_id"]!=$user_id){
            return show("30002","非此用户地址！","");
        }
        $Uaddress=Map::getLngLat($address["address"]);
        if($Uaddress==''){
            return show("30002","用户地址填写有误！","");
        }
        //验证距离
        $distance = calcDistance($Uaddress['lat'], $Uaddress['lng'],$shop['latitude'],$shop['longitude']);
        if($distance > ($shop->shopinfo->spend_distance)){
            return show("30001","不在配送范围！","");
        }
        //验证价格(除非你有更好的方法否则别乱来)
        $top_amount=$top_price = 0;
        foreach($cart['dish'] as $k=>$v)
        {
            $dishes = ShopDish::find($v['dishes_id']);
            if($dishes) {
                $dishes = $dishes->toArray();
                if ($dishes['is_attr'] == 1) {
                    //获取数据库的规格计算
                    $ShopDishAttribute = ShopDishAttribute::where('dish_id', $dishes['id'])->get();
                    $spec_price = 0;
                    foreach ($ShopDishAttribute as $k2 => $v2) {
                        foreach (explode(',', $v2['spec']) as $k3 => $v3) {
                            $spec = explode('|', $v3);
                            //获取购物车的规格计算
                            $cart_dish_spec = explode(',', $cart['dish'][$k]['spec']);
                            foreach ($cart_dish_spec as $k4 => $v4) {
                                $cart_spec = explode('|', $v4);
                                if ($cart_spec[0] == $spec[0]) {
                                    $spec_price += floatval($spec[1]);
                                }
                            }
                        }
                    }
                    //（规格价+基础价）* 数量 * 折扣
                    $top_amount += ($spec_price + $dishes['price']) * $cart['dish'][$k]['goods_number'] * $dishes['discount'];
                    $top_price += ($spec_price + $dishes['price']) * $cart['dish'][$k]['goods_number'];
                } else {
                    $top_amount += $dishes['price'] * $cart['dish'][$k]['goods_number'] * $dishes['discount'];
                    $top_price += $dishes['price'] * $cart['dish'][$k]['goods_number'];
                }
            }

        }
        //强转防止溢出
        $top_amount = round($top_amount,2)+$shop->shopinfo->spend;
        if($top_amount!=$cart['top_price']){
            return show("30003","购物车异常！",["top_price" => $top_amount]);
        }
        //未达起送价！
        if($top_amount<$shop->shopinfo->min_spend){
            return show("30003","未达起送价！");
        }
        //生成订单
        $insert=Order::create([
            "user_id"=>$user_id,      //用户id
            "shop_id"=>$cart["shop_id"],//商铺id
            "order_type"=>0,            //外卖
            "order_number"=>randID(),   //订单编号
            "order_status"=>1,          //订单状态
            "note"=>$cart['note'],      //订单备注
            "address_id"=>  $cart['address_id'], //配送地址id
            "order_price"=> $top_price+$shop->shopinfo->spend,         //订单总价
            "order_amount"=>$top_amount,       //实际价格
            "product_type"=>1,                 //餐饮模块（1）
        ]);
        //处理详情
        foreach($cart['dish'] as $k=>$v){
            $cart['dish'][$k]['order_id']=$insert['id'];
            $cart['dish'][$k]['amount']  = $cart['dish'][$k]['sell_price'] = $v['goods_number']*$v['price'];
        }
        DB::table('order_details')->insert($cart["dish"]);
        if($coupon_id){//使用优惠券
            $activity =new Activity();
            $activity->activity($insert['id'],2,$coupon_id);
        }
        return show("200","下单成功",["order_id"=>$insert['id'],"money"=>$top_amount,"order_type"=>0]);
        }catch (\Exception $e){
            dd($e->getMessage());
        }
    }

    //申请退款
    public function  applyForRefund($id,$token=false){
        //验证用户
        if($token){//token验证
            $WeixinUser = WeixinUser::where('token',$token)->first();
            if(!$WeixinUser){
                return show(30001,"无效token！");
            }else{
                $user= UserCheck::find($WeixinUser->user_id);
                if(!$user){
                    return show(30001,"用户不存在！");
                }
            }
            $user_id = $user->id;
        }else{//auth验证
            if(!Auth::id()){
                return show(30001,'请先登录');
            }
            $user_id = Auth::id();
        }
        //验证订单
        $order = Order::where('order_type',0)->where('order_status',2)->find($id);
        if(!$order){
            return show(30001,'订单验证错误，不允许申请');
        }else{
            if($user_id != $order->user_id){
                return show(30001,'没权限！');
            }
            $order->order_status = -1;
            $order->save();
            //通知商家
            return show(200,'申请成功，请耐心等待');
        }
    }

    //确认收货
    public function confirmReceipt($id,$token=false){
        //验证用户
        if($token){//token验证
            $WeixinUser = WeixinUser::where('token',$token)->first();
            if(!$WeixinUser){
                return show(30001,"无效token！");
            }else{
                $user= UserCheck::find($WeixinUser->user_id);
                if(!$user){
                    return show(30001,"用户不存在！");
                }
            }
            $user_id = $user->id;
        }else{//auth验证
            if(!Auth::id()){
                return show(30001,'请先登录');
            }
            $user_id = Auth::id();
        }
        //验证订单
        $order = Order::where('order_type',0)->where('order_status',3)->find($id);
        if(!$order){
            return show(30001,'订单验证错误，不允许确认');
        }else{
            if($user_id != $order->user_id){
                return show(30001,'没权限！');
            }
            $order->order_status = 4;
            $order->save();
            //加钱加流水
            $shop =Shop::find($order->shop_id);
            if($shop){
                $money = new MoneyChange();
                $money->add_money($shop->user_id,$order->order_price,1,'（用户确定）订单编号：'.$order->order_number,0,'外卖',$order->id);
            }
            //数据库自增
            $sqladd = new SqlIncrement();
            $sqladd->dishIncrement($id);
            //通知商家
            return show(200,'确认成功');
        }
    }


    //确定接单
    public function sureOrder($id,$token=false){
        if(!Auth::id()){
            return show(30001,'请先登录');
        }
        //确认人ID
        $user_id = Auth::id();
        //验证订单
        $order = Order::where('order_type',0)->find($id);
        if(!$order){
            return show(30001,'订单验证错误，订单不存在');
        }else{
            $Shop = Shop::find($order->shop_id);
            if(!$Shop){
                return show(30001,'订单验证错误，商家不存在');
            }
            if($user_id != $Shop->user_id){
                return show(30001,'没权限！');
            }
            if($order->order_status == 2){
                $order->order_status = 3;
                $order->save();
                //通知商家
                return show(200,'确定接单成功');
            }else if($order->order_status == 3){
                return show(200,'您确定接单，请勿重复提交');
            }else{
                return show(30001,'订单验证错误，不允许接单');
            }

        }
    }

    //同意退款sureForRefund
    public function sureForRefund($id,$token=false){
        if(!Auth::id()){
            return show(30001,'请先登录');
        }
        //确认人ID
        $user_id = Auth::id();
        //验证订单
        $order = Order::whereIn('order_type',[0,1])->find($id);
        if(!$order){
            return show(30001,'订单验证错误，订单不存在');
        }else{
            $Shop = Shop::find($order->shop_id);
            if(!$Shop){
                return show(30001,'订单验证错误，商家不存在');
            }
            if($user_id != $Shop->user_id){
                return show(30001,'没权限！');
            }
            if($order->order_status == -1){
                $order->order_status = -2;
                $order->save();
                //加流水
                $money = new MoneyChange();
                $money->add_money($order->user_id,$order->order_amount,1,'（商家同意退款）订单编号：'.$order->order_number,0,'退款');
                return show(200,'同意成功');
            }else if($order->order_status == -2){
                return show(200,'您已同意过退款，请勿重复提交');
            }else{
                return show(30001,'订单验证错误，不允许同意退款');
            }
        }
    }

}
